import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';

class YQDatePicker extends StatefulWidget {
  final String placeholder;
  final DateTime? initialDate;
  final DateTime? firstDate;
  final DateTime? lastDate;
  final Function(DateTime)? onDateSelected;
  final TextStyle? textStyle;
  final TextStyle? placeholderStyle;

  const YQDatePicker({
    Key? key,
    this.placeholder = "请选择日期",
    this.initialDate,
    this.firstDate,
    this.lastDate,
    this.onDateSelected,
    this.textStyle,
    this.placeholderStyle,
  }) : super(key: key);

  @override
  State<YQDatePicker> createState() => _YQDatePickerState();
}

class _YQDatePickerState extends State<YQDatePicker> {
  DateTime? _selectedDate;
  late DateFormat _dateFormat;
  bool _initialized = false;

  final List<String> _chineseMonths = [
    '一月', '二月', '三月', '四月', '五月', '六月',
    '七月', '八月', '九月', '十月', '十一月', '十二月'
  ];

  @override
  void initState() {
    super.initState();
    _selectedDate = widget.initialDate;
    _initializeDateFormatting();
  }

  Future<void> _initializeDateFormatting() async {
    await initializeDateFormatting('zh_CN', null);
    _dateFormat = DateFormat('yyyy-MM-dd');
    setState(() {
      _initialized = true;
    });
  }

  Widget _buildPickerItem(String text) {
    return Center(
      child: Text(
        text,
        style: const TextStyle(fontSize: 16),
      ),
    );
  }

  void _showDatePicker() {
    if (!_initialized) return;

    final now = DateTime.now();
    final year = _selectedDate?.year ?? now.year;
    final month = _selectedDate?.month ?? now.month;
    final day = _selectedDate?.day ?? now.day;

    final years = List.generate(100, (index) => (now.year - 50 + index).toString());
    final months = List.generate(12, (index) => _chineseMonths[index]);
    final days = List.generate(
      DateTime(year, month + 1, 0).day,
      (index) => (index + 1).toString(),
    );

    int selectedYearIndex = years.indexOf(year.toString());
    int selectedMonthIndex = month - 1;
    int selectedDayIndex = day - 1;

    // 设置初始日期
    _selectedDate = DateTime(year, month, day);

    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 300,
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          color: Colors.white,
          child: SafeArea(
            top: false,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  height: 44,
                  decoration: BoxDecoration(
                    color: Colors.grey[200],
                    border: Border(
                      bottom: BorderSide(
                        color: Colors.grey[300]!,
                        width: 0.5,
                      ),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      CupertinoButton(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: const Text(
                          '取消',
                          style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
                        ),
                        onPressed: () => Navigator.of(context).pop(),
                      ),
                      CupertinoButton(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: const Text(
                          '确定',
                          style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                          if (_selectedDate != null) {
                            widget.onDateSelected?.call(_selectedDate!);
                          }
                        },
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Row(
                    children: [
                      Expanded(
                        child: CupertinoPicker(
                          itemExtent: 32,
                          onSelectedItemChanged: (index) {
                            final newYear = int.parse(years[index]);
                            final newDate = DateTime(
                              newYear,
                              selectedMonthIndex + 1,
                              selectedDayIndex + 1,
                            );
                            setState(() {
                              _selectedDate = newDate;
                            });
                          },
                          children: years.map((year) => _buildPickerItem(year)).toList(),
                          scrollController: FixedExtentScrollController(
                            initialItem: selectedYearIndex,
                          ),
                        ),
                      ),
                      Expanded(
                        child: CupertinoPicker(
                          itemExtent: 32,
                          onSelectedItemChanged: (index) {
                            final newMonth = index + 1;
                            final newDate = DateTime(
                              year,
                              newMonth,
                              selectedDayIndex + 1,
                            );
                            setState(() {
                              _selectedDate = newDate;
                            });
                          },
                          children: months.map((month) => _buildPickerItem(month)).toList(),
                          scrollController: FixedExtentScrollController(
                            initialItem: selectedMonthIndex,
                          ),
                        ),
                      ),
                      Expanded(
                        child: CupertinoPicker(
                          itemExtent: 32,
                          onSelectedItemChanged: (index) {
                            final newDay = index + 1;
                            final newDate = DateTime(
                              year,
                              month,
                              newDay,
                            );
                            setState(() {
                              _selectedDate = newDate;
                            });
                          },
                          children: days.map((day) => _buildPickerItem(day)).toList(),
                          scrollController: FixedExtentScrollController(
                            initialItem: selectedDayIndex,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    if (!_initialized) {
      return const SizedBox.shrink();
    }

    return GestureDetector(
      onTap: _showDatePicker,
      child: Container(
        height: 36,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Text(
              _selectedDate != null
                  ? _dateFormat.format(_selectedDate!)
                  : widget.placeholder,
              style: _selectedDate != null
                  ? (widget.textStyle ??
                      const TextStyle(fontSize: 16, color: Colors.black))
                  : (widget.placeholderStyle ??
                      const TextStyle(fontSize: 16, color: Colors.grey)),
            ),
          ],
        ),
      ),
    );
  }
} 